package com.m.rule;

import com.m.IRule;
import groovy.lang.GroovyClassLoader;

import java.io.File;

/**
 * 功能: <br/>
 *
 * @author miracle
 */
public class RuleLoader {
    private static RuleLoader ruleLoader = new RuleLoader();
    private GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

    public static RuleLoader getInstance() {
        return ruleLoader;
    }

    private RuleLoader() {
        init();
    }

    /**
     * 初始化: 加载基本规则
     */
    private void init() {
//        System.out.println(AndRules.class);
//        System.out.println(OrRules.class);
//        System.out.println(AbstractDim.class);
    }
    /**
     * 根据groovy文件路径生成IRule的实现
     * @param filePath
     * @return
     * @throws Exception
     */
    public IRule getIRuleFromPackage(String filePath) throws Exception {
//        URL url = this.getClass().getClassLoader().getResource(filePath);
//        Class<?> clazz = groovyClassLoader.parseClass(new GroovyCodeSource(url));
        Class<?> clazz = groovyClassLoader.parseClass(new File(filePath));
        if (clazz != null) {
            Object instance = clazz.newInstance();
            if (instance != null) {
                if (instance instanceof IRule) {
                    return (IRule) instance;
                }
            }
        }
        throw new IllegalArgumentException("读取规则文件异常");

//        Class script = new GroovyScriptEngine("C:\\Users\\miracle_j\\Desktop\\temp", this.getClass().getClassLoader())
//                .loadScriptByName("com/m/demo/LoginRule.groovy");
//        System.out.println(script);
//        return null;
    }
}
